package service_common

import (
	"github.com/gin-gonic/gin"
	uuid "github.com/satori/go.uuid"
	"tools-api/src/buisiness/model"
	"tools-api/src/common/db/database"
	"xorm.io/xorm"
)

func VisitTrack(ip string, uid string) (gin.H, error) {
	session := database.ToolsEngine.NewSession()
	defer func(s *xorm.Session) {
		_ = s.Close()
	}(session)
	err := session.Begin()
	if err != nil {
		return nil, err
	}
	var record model.VisitTrack
	if uid == "" {
		uid = uuid.NewV4().String() // 新访客，创建唯一ID
	}

	// 已有访客，更新访问记录
	_, err = session.Where("uid = ?", uid).Get(&record) // 此处不带ip，是因为ip可能会飘
	if err != nil {
		_ = session.Rollback()
		return nil, err
	}

	if record.Id <= 0 {
		// 访客ID无效，创建新记录
		record.Uid = uid
		record.Ip = ip
		record.Count = 1
		if _, err = session.Insert(&record); err != nil {
			_ = session.Rollback()
			return nil, err
		}
	} else {
		// 更新访问次数
		record.Count++
		record.Ip = ip // 更新IP地址（如果有变化）

		if _, err = session.ID(record.Id).Update(&record); err != nil {
			_ = session.Rollback()
			return nil, err
		}
	}

	// 提交事务
	if err = session.Commit(); err != nil {
		return nil, err
	}

	// 获取统计信息
	totalUsers, err := database.ToolsEngine.Where("ip!=?", "::1").Count(new(model.VisitTrack))
	if err != nil {
		return nil, err
	}
	var totalCount int64
	_, err = database.ToolsEngine.Table(model.VisitTrack{}).Where("ip!=?", "::1").Select("SUM(count)").Get(&totalCount)
	if err != nil {
		return nil, err
	}
	return gin.H{
		"user":  totalUsers,
		"count": totalCount,
		"uid":   record.Uid,
	}, nil
}
